let server = require("express")();
let url = require("url");
let mysql = require("mysql");
let expressStatic = require("express-static");

let port = 82;
let sql = mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"123456",
	database:"kaola",
	timezone:"08:00"
});

sql.connect();


server.get(`/index`, (req, res) => {            // 请求和响应
    sql.query(`SELECT * FROM shoplist`, (error, data) => {
        if (error) {
            console.log(error);
            res.end("error")
        } else {
            console.log("返回数据成功");
            res.end(JSON.stringify(data))
        }
    })
})


// 注册
server.get("/regi",(request,response)=>{

	let username = url.parse(request.url,true).query.username;
	let password = url.parse(request.url,true).query.password;

	if(username && password){
		sql.query(`SELECT * FROM users WHERE username="${username}"`,(error,data)=>{
			if(data.length){
				response.end(`repeat`);
			}
			else{
				// 写入新用户数据
				sql.query(`INSERT INTO users (username,password) VALUES ("${username}","${password}")`,(error,data)=>{
					if(error){
						response.end("database error");
						console.log(error)
					}
					else{
						// 反解析后向前端返回JSON字符串
						response.end(`success`)
					}
				})
			}
		})
	}
	else{
		response.end("error")
	}
})

server.get("/sign",(request,response)=>{
	let username = url.parse(request.url,true).query.username;
	let password = url.parse(request.url,true).query.password;
	if(username && password){
		sql.query(`SELECT * FROM users WHERE username="${username}" AND password="${password}"`,(error,data)=>{
			if(data.length){
				response.end(`success`)
			}
		})
	}
	else{
		response.end("error")
	}
	
})

//详情页单价与介绍获取
server.get("/detail", (req, res) => {
	let sd = url.parse(req.url, true).query.sd;
	sql.query(`SELECT introduce,pirce FROM shoplist WHERE shoplistId="${sd}"`,(error,data)=>{
		if (error) {
            console.log(error);
            res.end("error")
        } else {
			console.log("返回数据成功");
            res.end(JSON.stringify(data))
        }
	})
});

server.get("/shop", (req, res) => {
	let ad = url.parse(req.url, true).query.ad;
	sql.query(`SELECT introduce,pirce FROM shoplist WHERE shoplistId="${ad}"`,(error,data)=>{
		if (error) {
            console.log(error);
            res.end("error")
        } else {
			console.log("返回数据成功");
            res.end(JSON.stringify(data))
        }
	})
});

server.get("/order", (req, res) => {
	let ad = url.parse(req.url, true).query.ad;
	sql.query(`SELECT introduce,pirce FROM shoplist WHERE shoplistId="${ad}"`,(error,data)=>{
		if (error) {
            console.log(error);
            res.end("error")
        } else {
			console.log("返回数据成功");
            res.end(JSON.stringify(data))
        }
	})
});


server.use(expressStatic(__dirname + '/static'))
server.listen(port);
console.log(`开放了${port}`)

// close 当服务器关闭时，触发事件,(注意：不是用户断开链接时),当然服务器开了谁随便关